//
//  PublishShopViewController.m
//  KingSelected
//
//  Created by 杨鹏 on 2023/10/30.
//

#import "PublishShopViewController.h"
#import "PhotosCollection.h"
#import "TZImagePickerController.h"
#import "VideoCell.h"

@interface PublishShopViewController ()<TZImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UIScrollView *scrollview;
@property (nonatomic, strong) UITextView *textview;
@property (nonatomic, strong) UILabel *limitLabel;
@property (nonatomic, strong) UIButton *publishBtn;
@property (nonatomic, strong) PhotosCollection *photoCV;
@property (nonatomic, strong) NSMutableArray *photoArr;
@property (nonatomic, strong) NSMutableArray *selectedAsset;
/// 图片预览图
@property (nonatomic, strong) NSMutableArray *thumbnailPicUrl;
@property (nonatomic, copy) NSString *videoUrl;
/// 视频预览图
@property (nonatomic, copy) NSString *videoPicUrl;
@property (nonatomic, strong) VideoCell *videoView;
@property (nonatomic, strong) PHAsset *videoAsset;
@property (nonatomic, strong) UITextField *priceTF;

@property (nonatomic, assign) CGFloat h;
@end

@implementation PublishShopViewController

- (void)initDidLoad {
    self.navigationTitle = @"发布商品";
}

- (void)initViews {
    [self.view addSubview:self.scrollview];
    [self.scrollview addSubview:self.textview];
    [self.scrollview addSubview:self.limitLabel];
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 175, kWidthForScreen, 1)];
    line1.backgroundColor = kRGB(0xF3F3F3);
    [self.scrollview addSubview:line1];
    
    UILabel *priceLabel = [[UILabel alloc] init];
    priceLabel.textColor = kRGB(0x333333);
    priceLabel.font = kFontMediium(14);
    priceLabel.text = @"售价";
    [priceLabel sizeToFit];
    [self.scrollview addSubview:priceLabel];
    [self.scrollview addSubview:self.priceTF];
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(0, 230, kWidthForScreen, 1)];
    line2.backgroundColor = kRGB(0xF3F3F3);
    [self.scrollview addSubview:line2];
    
    [self.scrollview addSubview:self.videoView];
    
    [self.scrollview addSubview:self.photoCV];
    
    [self.view addSubview:self.publishBtn];
    
    [self.limitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.textview);
        make.top.mas_equalTo(self.textview.mas_bottom).offset(10);
    }];
    [priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(16);
        make.top.mas_equalTo(line1.mas_bottom).offset(20);
    }];
    [self.priceTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(-16);
        make.centerY.equalTo(priceLabel);
        make.height.mas_equalTo(30);
        make.leading.mas_equalTo(priceLabel.mas_trailing).offset(20);
    }];
    [self.publishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(230, 40));
        make.centerX.mas_equalTo(0);
        make.bottom.mas_equalTo(-20-kHeightForTabbarExtra);
    }];
    /// 10 + 130 + 10 + 15 + 10 + 20 + 15 + 20 + 16 + 84 + 12 + (kWidthForScreen-52) + 20
    self.h = 10 + 130 + 10 + 15 + 10 + 20 + 15 + 20 + 16 + (kWidthForScreen-52)/3 + 12 + (kWidthForScreen-52) + 20;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.scrollview.contentSize = CGSizeMake(kWidthForScreen, self.h);
}

- (void)initRequestData {
    UIImage *img = [UIImage imageNamed:@"uploadPhoto"];
    [self.photoArr addObject:img];
    
    self.photoCV.dataArr = self.photoArr;
    [self.photoCV reloadData];
}

/// 编辑
- (void)setModel:(ShopModel *)model {
    _model = model;
    self.textview.text = model.goodsIntroduction;
    self.priceTF.text = model.sellingPrice;
    NSInteger a = 0;
    if (model.videoPicUrl) {
        self.videoView.imageUrl = model.videoPicUrl;
        self.videoPicUrl = model.videoPicUrl;
        self.videoUrl = model.video;
        a += 1;
    }
    if (model.imgUrl.count > 0) {
        [self.photoArr removeAllObjects];
        [self.thumbnailPicUrl removeAllObjects];
        [self.photoArr addObjectsFromArray:model.imgUrl];
        
        a += model.imgUrl.count;
        if (a < 9) {
            [self.photoArr addObject:[UIImage imageNamed:@"uploadPhoto"]];
        }
        [self.thumbnailPicUrl addObjectsFromArray:model.imgThumbnailUrl];
        [self.photoCV reloadData];
    }
}

#pragma mark - action
/// type 0 photo 1video
- (void)showImagePicker:(int)type {
    TZImagePickerController *imagepicker = [[TZImagePickerController alloc] initWithMaxImagesCount:self.videoUrl.length > 0 ? 8-self.selectedAsset.count : 9-self.selectedAsset.count delegate:self];
//    imagepicker.selectedAssets = self.selectedAsset;
    imagepicker.navigationBar.barTintColor = [UIColor blackColor];
    imagepicker.navigationBar.tintColor = [UIColor whiteColor];
    imagepicker.naviTitleColor = [UIColor whiteColor];
    imagepicker.naviTitleFont = kFontCarter(20);
    imagepicker.title = type == 0 ? @"选择图片" : @"选择视频";
    imagepicker.iconThemeColor = kBgColor;
    imagepicker.oKButtonTitleColorNormal = kBgColor;
    imagepicker.allowCrop = NO;
    imagepicker.allowTakeVideo = NO;
    imagepicker.allowTakePicture = YES;
    imagepicker.allowPickingVideo = type == 1;
    imagepicker.allowPickingImage = type == 0;
    imagepicker.allowPickingOriginalPhoto = NO;
    imagepicker.allowPickingMultipleVideo = NO;
    imagepicker.videoPreviewPageDidLayoutSubviewsBlock = ^(UIButton *playButton, UIView *toolBar, UIButton *editButton, UIButton *doneButton) {
        
    };
    imagepicker.modalPresentationStyle = UIModalPresentationFullScreen;
    imagepicker.delegate = self;
    imagepicker.sortAscendingByModificationDate = YES;
    [self presentViewController:imagepicker animated:YES completion:^{
            
    }];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    for (int i = 0; i < photos.count; i++) {
        UIImage *img = photos[i];
//        NSData *imgData = [img compressWithMaxLength];
        NSData *imgData = UIImageJPEGRepresentation(img, 0.5);
        [YPProgressHud showHudInview:self.view];
        [NetManager uploadWithURL:URL(@"common/uploadPic") parameters:nil fileData:@[imgData] fileNames:@[@"file"] mimeType:nil progress:nil success:^(id  _Nullable responseObject) {
            NSString *picUrl = responseObject[@"picUrl"];
            if (picUrl.length > 0) {
                [self.photoArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj isKindOfClass:[UIImage class]]) {
                        [self.photoArr removeObjectAtIndex:idx];
                    }
                }];
                [self.photoArr addObject:picUrl];
                [self.thumbnailPicUrl addObject:responseObject[@"thumbnailPicUrl"]];
                if ((self.videoUrl.length > 0 && self.photoArr.count < 8) || (self.videoUrl.length <= 0 && self.photoArr.count < 9)) {
                    [self.photoArr addObject:[UIImage imageNamed:@"uploadPhoto"]];
                }
                [self.selectedAsset addObject:assets[i]];
            }
            self.photoCV.dataArr = self.photoArr;
            [self.photoCV reloadData];
            [YPProgressHud hideHudForView:self.view];
        } failure:^(NSError * _Nonnull error) {
            [YPProgressHud hideHudForView:self.view];
        }];
    }
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset {
    [YPProgressHud showHudInview:self.view];
    [[TZImageManager manager] getVideoOutputPathWithAsset:asset success:^(NSString *outputPath) {
        NSData *data = [NSData dataWithContentsOfFile:outputPath];
        [NetManager uploadWithURL:URL(@"common/uploadVideo") parameters:nil fileData:@[data] fileNames:@[@"file"] mimeType:@"1" progress:nil success:^(id  _Nullable responseObject) {
            [YPProgressHud hideHudForView:self.view];
            if (responseObject[@"videoUrl"]) {
                self.videoView.image = coverImage;
                self.videoUrl = responseObject[@"videoUrl"];
                self.videoPicUrl = responseObject[@"videoPicUrl"];
                self.videoAsset = asset;
            }
        } failure:^(NSError * _Nonnull error) {
            kShowText(error.userInfo[kHttpErrorReason]);
            [YPProgressHud hideHudForView:self.view];
        }];
    } failure:^(NSString *errorMessage, NSError *error) {
        kShowText(error.userInfo[kHttpErrorReason]);
        [YPProgressHud hideHudForView:self.view];
    }];
}

- (void)publishAction {
    if (self.textview.text.length <= 0) {
        kShowText(@"请输入商品介绍");
        return;
    }
    if (self.priceTF.text.length <= 0) {
        kShowText(@"请输入商品价格");
        return;
    }
    if (self.photoArr.count <= 1) {
        kShowText(@"请上传商品图片");
        return;
    }
    NSMutableArray *imaArr = [NSMutableArray array];
    [self.photoArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![obj isKindOfClass:[UIImage class]]) {
            [imaArr addObject:obj];
        }
    }];
    NSString *imagUrl = [imaArr componentsJoinedByString:@","];
    NSString *thumUrl = [self.thumbnailPicUrl componentsJoinedByString:@","];
    [NET publishGoodsWithGoodsId:self.model.goodsId goodsIntroduction:self.textview.text sellingPrice:self.priceTF.text imgUrl:imagUrl imgThumbnailUrl:thumUrl video:self.videoUrl videoImgUrl:self.videoPicUrl success:^(id  _Nonnull responseObject) {
        kShowText(self.model ? @"更新成功" : @"发布成功");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    } failure:^(NSError * _Nonnull error) {
        kShowText(error.userInfo[kHttpErrorReason]);
    }];
}

#pragma mark - 懒加载
- (UIScrollView *)scrollview {
    if (!_scrollview) {
        _scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kWidthForScreen, kHeightForScreen-20-kHeightForTabbarExtra-40-17-kHeightForNaigation)];
        _scrollview.backgroundColor = [UIColor whiteColor];
        _scrollview.bounces = YES;
        _scrollview.alwaysBounceVertical = YES;
        _scrollview.showsVerticalScrollIndicator = NO;
        _scrollview.showsHorizontalScrollIndicator = NO;
    }
    return _scrollview;
}

- (UITextView *)textview {
    if (!_textview) {
        _textview = [[UITextView alloc] initWithFrame:CGRectMake(16, 10, kWidthForScreen-32, 130)];
        _textview.backgroundColor = [UIColor whiteColor];
        _textview.font = kFontRegula(14);
        _textview.textColor = kRGB(0x333333);
        _textview.textAlignment = NSTextAlignmentLeft;
        _textview.showsVerticalScrollIndicator = NO;
        @weakify(self)
        [_textview.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
         @strongify(self)
            if (x.length > 300) {
                self.textview.text = [x substringToIndex:300];
            }
            self.limitLabel.text = [NSString stringWithFormat:@"%ld/300",self.textview.text.length];
        }];
        
        UILabel *placeHolderLabel = [[UILabel alloc] init];
        placeHolderLabel.text = @"请输入商品介绍";
        placeHolderLabel.numberOfLines = 0;
        placeHolderLabel.font = kFontRegula(14);
        placeHolderLabel.textColor = kRGB(0x999999);
        [placeHolderLabel sizeToFit];
        [_textview addSubview:placeHolderLabel];
        [_textview setValue:placeHolderLabel forKey:@"_placeholderLabel"];
    }
    return _textview;
}

- (UILabel *)limitLabel {
    if (!_limitLabel) {
        _limitLabel = [[UILabel alloc] init];
        _limitLabel.font = kFontRegula(14);
        _limitLabel.textColor = kRGB(0x999999);
        _limitLabel.text = @"0/300";
        [_limitLabel sizeToFit];
    }
    return _limitLabel;
}
- (UIButton *)publishBtn {
    if (!_publishBtn) {
        _publishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _publishBtn.backgroundColor = kBgColor;
        _publishBtn.layer.cornerRadius = 20;
        _publishBtn.layer.masksToBounds = YES;
        [_publishBtn setTitle:@"发布" forState:UIControlStateNormal];
        [_publishBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _publishBtn.titleLabel.font = kFontMediium(16);
        @weakify(self)
        [[_publishBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self)
            [self publishAction];
        }];
    }
    return _publishBtn;
}

- (PhotosCollection *)photoCV {
    if (!_photoCV) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake((kWidthForScreen-52)/3, (kWidthForScreen-52)/3);
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 0;
        _photoCV = [[PhotosCollection alloc] initWithFrame:CGRectMake(16, 10 + 130 + 10 + 15 + 10 + 20 + 15 + 20 + 16 + (kWidthForScreen-52)/3 + 12, kWidthForScreen-32, kWidthForScreen-52+20) collectionViewLayout:layout];
        @weakify(self)
        [_photoCV.didSelectedCellSubject subscribeNext:^(NSIndexPath *x) {
         @strongify(self)
            id obj = self.photoArr[x.item];
            if ([obj isKindOfClass:[UIImage class]]) {
                [self showImagePicker:0];
            }
        }];
        [_photoCV setDeleteVideoBlock:^(NSString * _Nonnull imageUrl) {
            @strongify(self)
            [self.photoArr enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isKindOfClass:[NSString class]] && [obj isEqualToString:imageUrl]) {
                    [self.photoArr removeObjectAtIndex:idx];
                    [self.photoCV reloadData];
                    [self.thumbnailPicUrl removeObjectAtIndex:idx];
                }
            }];
        }];
    }
    return _photoCV;
}

- (VideoCell *)videoView {
    if (!_videoView) {
        _videoView = [[VideoCell alloc] initWithFrame:CGRectMake(16, 246, (kWidthForScreen-52)/3, (kWidthForScreen-52)/3)];
        @weakify(self)
        [_videoView setShowVideoPickerBlcok:^{
         @strongify(self)
            [self showImagePicker:1];
        }];
        [_videoView setDeleteVideoBlock:^{
            @strongify(self)
            self.videoUrl = nil;
        }];
        [_videoView setPlayVideoBlock:^{
            @strongify(self)
            TZVideoPlayerController *vc = [[TZVideoPlayerController alloc] init];
            TZAssetModel *model = [TZAssetModel modelWithAsset:self.videoAsset type:TZAssetModelMediaTypeVideo];
            vc.model = model;
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:vc animated:YES completion:^{
            }];
        }];
    }
    return _videoView;
}

- (NSMutableArray *)photoArr {
    if (!_photoArr) {
        _photoArr = [NSMutableArray array];
    }
    return _photoArr;
}
- (NSMutableArray *)thumbnailPicUrl {
    if (!_thumbnailPicUrl) {
        _thumbnailPicUrl = [NSMutableArray array];
    }
    return _thumbnailPicUrl;
}
- (NSMutableArray *)selectedAsset {
    if (!_selectedAsset) {
        _selectedAsset = [NSMutableArray array];
    }
    return _selectedAsset;
}


- (UITextField *)priceTF {
    if (!_priceTF) {
        _priceTF = [[UITextField alloc] initWithFrame:CGRectZero];
        _priceTF.textColor = kRGB(0xF15757);
        _priceTF.font = kFontMediium(14);
        _priceTF.placeholder = @"请输入商品价格";
        _priceTF.borderStyle = UITextBorderStyleNone;
        _priceTF.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _priceTF;
}

@end
